//
//  SYS_MessageSendSearchVC.m
//  System_App
//
//  Created by 魏配军 on 2017/12/6.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageSendSearchVC.h"
#import "SYS_MemberModel.h"
#import "SYS_MessageHomeCell.h"
#import "SYS_MemberDetailVC.h"

@interface SYS_MessageSendSearchVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSInteger page;
    BOOL isLast;
}
/*************搜索视图************/
@property (nonatomic, strong) SYS_SearchView *searchView;
/*************无数据视图************/
@property (nonatomic, strong) SYS_DisplayWithBlankView *alertView;
@property (nonatomic, strong) DSNewTableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation SYS_MessageSendSearchVC

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
    [self initWithUI];
    
}


#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"消息";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(backToPrevious)];
    self.view.backgroundColor = DGHColor(242, 242, 242);
}

#pragma mark   -------  UI  ---------
-(void) initWithUI
{
    _searchView = [[SYS_SearchView alloc] initWithFrame:CGRectMake(0, 10, SCREENWIDTH, 40)];
    _searchView.placeholder=@"请输入您要查找的联系人";
    _searchView.isClickChange=NO;
    _searchView.inputTF.tag=99999;
    _searchView.inputTF.delegate=self;
    [self.view addSubview:_searchView];
    
    _mainTableView=[[DSNewTableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchView.frame)+10, SCREENWIDTH, SCREENHEIGHT-124) style:UITableViewStylePlain];
    _mainTableView.delegate=self;
    _mainTableView.dataSource=self;
    _mainTableView.backgroundColor=DSCOLOR_WHITE;
    _mainTableView.showsHorizontalScrollIndicator=NO;
    _mainTableView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:_mainTableView];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"SYS_MessageHomeCell" bundle:nil] forCellReuseIdentifier:@"SYS_MessageHomeCell"];
    
    page=1;
    _dataArray=[NSMutableArray array];
    [self getStoreMembersList];
    
    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        page=1;
        [self getStoreMembersList];
        [_mainTableView.mj_header endRefreshing];
    }];
    
    _mainTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (_dataArray.count % 20 == 0 && !isLast) {
            page++;
            [self getStoreMembersList];
        }
        else
        {
            [MBProgressHUD showSuccess:@"当前页已是最新" toView:self.view];
        }
        [_mainTableView.mj_footer endRefreshing];
    }];
    
    _alertView=[[SYS_DisplayWithBlankView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _alertView.photo.image=[UIImage imageNamed:@"message_lianxirenbucz"];
    _alertView.title.text=@"你查找的联系人不存在，请重新搜索~";
    _alertView.center=CGPointMake(_mainTableView.center.x, 140);
    _alertView.hidden=YES;
    [self.view addSubview:_alertView];
    
    //添加文本框通知中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gosave:) name:UITextFieldTextDidChangeNotification object:nil];
}

// 检测textfiled值得变化
- (void)gosave:(NSNotification *) Notification{
    UITextField * textField = Notification.object;
    
    if (textField.tag == 99999) {
        page=1;
//        if (textField.text.length>0) {
            [self getStoreMembersList];

//        }else{
//
//        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    if (textField.tag == 99999) {
        page=1;
        [self getStoreMembersList];
    }
    return YES;
}


#pragma mark -------  请求会员消息-------------
- (void)getStoreMembersList
{
    UITextField *textFiled=[self.view viewWithTag:99999];
    NSString *search=@"";
    if (textFiled.text.length>0) {
        search=textFiled.text;
    }
    
    NSString *session=[SYS_LoginModel instance].sessionInfo.session;
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setValue:@(page) forKey:@"pageNumber"];
    [dic setValue:@(20) forKey:@"pageSize"];
    [dic setValue:session forKey:@"session"];
    [dic setValue:pid forKey:@"pid"];
    [dic setValue:search forKey:@"search"];

    [SYS_HttpUtility getMemberListRequest:dic success:^(id returnValue) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            if (page == 1) {
                [_dataArray removeAllObjects];
            }
            NSArray *array=returnValue[@"data"][@"list"];
            isLast=array.count?NO:YES;

            for (int i=0; i<array.count; i++) {
                SYS_MemberModel *model=[SYS_MemberModel mj_objectWithKeyValues:array[i]];
                [_dataArray addObject:model];
            }
            
            _alertView.hidden=_dataArray.count?YES:NO;
            [_mainTableView reloadData];
        }
        else
        {
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        RequestFailure;
    }];
}

#pragma mark tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"SYS_MessageHomeCell";
    SYS_MessageHomeCell *cell=(SYS_MessageHomeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell==nil) {
        cell=[[SYS_MessageHomeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    SYS_MemberModel *model=_dataArray[indexPath.row];
    cell.model=model;
    //点击Cell时背景不变蓝
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SYS_MemberModel *model=_dataArray[indexPath.row];
    SYS_MemberDetailVC *vc=[SYS_MemberDetailVC new];
    vc.userId=model.userId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}





-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}



@end
